# -*- coding: utf-8 -*-
"""
@Time ： 2024/8/1 13:12
@Auth ： 李天天
"""
import pytest
import time


def pytest_terminal_summary(terminalreporter, exitstatus, config):
    total = terminalreporter._numcollected
    passed = len(terminalreporter.stats.get('passed', []))
    failed = len(terminalreporter.stats.get('failed', []))
    errors = len(terminalreporter.stats.get('error', []))
    skipped = len(terminalreporter.stats.get('skipped', []))

    success_rate = passed / total * 100 if total > 0 else 0

    duration = time.time() - terminalreporter._sessionstarttime
    hours, remainder = divmod(duration, 3600)
    minutes, seconds = divmod(remainder, 60)
    formatted_duration = f"{int(hours):02}:{int(minutes):02}:{int(seconds):02}"

    # summary = (
    #     f"Total: {total}, "
    #     f"Passed: {passed}, "
    #     f"Failed: {failed}, "
    #     f"Errors: {errors}, "
    #     f"Skipped: {skipped}, "
    #     f"Success Rate: {success_rate:.2f}%, "
    #     f"Total Time: {formatted_duration}"
    # )
    summary = {
        "Total": total,
        "Passed": passed,
        "Failed": failed,
        "Errors": errors,
        "Skipped": skipped,
        "Deselected": total - passed - failed - errors - skipped,
        "SuccessRate": f'{success_rate:.2f}%',
        "TotalTime": formatted_duration
    }
    # terminalreporter.write_sep("=", "Test Summary")
    # terminalreporter.write_line(summary)
    print(summary)


# 全局变量用于跟踪进度
total_tests = 0
executed_tests = 0

def pytest_sessionstart(session):
    global total_tests, executed_tests
    total_tests = 0
    executed_tests = 0

def pytest_collection_finish(session):
    global total_tests
    # 在测试用例收集完成后，获取总的测试用例数量
    total_tests = len(session.items)
    print(f"Total tests collected: {total_tests}")

def pytest_runtest_logreport(report):
    global executed_tests, total_tests
    if report.when == 'call':
        # 在每个测试用例执行后，更新已执行用例计数并显示进度
        executed_tests += 1
        progress = executed_tests / total_tests * 100
        print(f"Progress: {executed_tests}/{total_tests} ({progress:.2f}%)")

def pytest_sessionfinish(session, exitstatus):
    print(f"Total tests: {total_tests}")
    print(f"Executed tests: {executed_tests}")